import { Component, OnInit, SimpleChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
    selector: 'app-nested-form',
    templateUrl: './nested-form.component.html',
    styleUrls: ['./nested-form.component.less'],
})
export class NestedFormComponent implements OnInit {
    validateForm: FormGroup;
    onlineServiceImg:any = '/assets/image/default/flowers.jpg';
    customerFile;
    userFile;
    userDocumentImg:any = '/assets/image/default/tree.jpg';
    reader = new FileReader();
    get support(): FormArray {
        return this.validateForm.get('support') as FormArray; // 明确转换为 FormArray
    }
    constructor(private fb: FormBuilder, private nzMessage: NzMessageService) {}

    ngOnInit(): void {
        this.initForm();
    }

    ngOnChanges(changes: SimpleChanges) {
        this.initForm();
        const technicalSupport = changes.technicalSupport.currentValue || {};
        if (technicalSupport && Object.keys(technicalSupport).length) {
            this.validateForm.patchValue({
                emailSwitch: technicalSupport.technical_support_email_show || false,
                email: technicalSupport.technical_support_email || null,
                officialWebsiteSwitch: technicalSupport.enterprise_website_show || false,
                officialWebsite: technicalSupport.enterprise_website || null,
                copyrightNoticeSwitch: technicalSupport.copyright_notice_show || false,
                copyrightNotice: technicalSupport.copyright_notice,
                supportSwitch: technicalSupport.technical_support_show || false,
                onlineServiceSwitch: technicalSupport.customer_service_qr_code_show || false,
                userDocumentSwitch: technicalSupport.user_document_show || false,
                userLicenseSwitch: technicalSupport.user_license_show || false,
                userLicense: technicalSupport.user_license,
            });
            this.onlineServiceImg = technicalSupport.customer_service_qr_code;
            this.userDocumentImg = technicalSupport.user_document;
            const supportArr = technicalSupport.technical_support === '' ? [] : Array.isArray(technicalSupport.technical_support) ? technicalSupport.technical_support : JSON.parse(technicalSupport.technical_support);
            while (this.support.length !== 0) {
                this.support.removeAt(0);
            }
            supportArr.forEach((item: any) => {
                this.support.push(this.createSupportGroup(item));
            });
        }
    }

    // 初始化表单
    initForm() {
        this.validateForm = this.fb.group({
            emailSwitch: [true, []],
            email: ['', [Validators.email]],
            officialWebsiteSwitch: [true, []],
            officialWebsite: ['', []],
            copyrightNoticeSwitch: [true, []],
            copyrightNotice: ['', []],
            supportSwitch: [true, []],
            support: this.fb.array([this.createSupportGroup()]),
            onlineServiceSwitch: [true, []],
            userDocumentSwitch: [true, []],
            userLicenseSwitch: [true, []],
            userLicense: ['', []],
        });
    }

    // 创建嵌套表单
    createSupportGroup(data?: {
        contact?: string;
        phone?: string;
        time?: string;
    }): FormGroup {
        return this.fb.group({
            contact: this.fb.control({
                value: data && data.contact ? data.contact : '',
                disabled: data ? true : false,
            }),
            phone: this.fb.control({
                value: data && data.phone ? data.phone : '',
                disabled: data ? true : false,
            }),
            time: this.fb.control({
                value: data && data.time ? data.time : '',
                disabled: data ? true : false,
            }),
            isEditing: [data ? false : true], // 编辑状态字段
        });
    }

    // 提交表单
    submitForm = ($event: any, value: any) => {
        $event.preventDefault();
        for (const key in this.validateForm.controls) {
            this.validateForm.controls[key].markAsDirty();
            this.validateForm.controls[key].updateValueAndValidity();
        }
        const formValue = this.validateForm.getRawValue();
        const invalid =
            formValue &&
            formValue.support.some((element) => {
                if (
                    element.phone === '' ||
                    element.contact === '' ||
                    element.time === ''
                ) {
                    this.nzMessage.error(
                        '请检查技术支持信息，技术支持联系人信息项均不能为空'
                    );
                    return true; // 停止遍历并标记为无效
                }
                return false;
            });

        if (invalid) {
            return; // 停止函数
        }

        if (this.validateForm.valid) {
            let emit = {
                ...formValue,
                customer_service_qr_code: this.customerFile,
                user_document: this.userFile,
            }
            // this.changeConfig.emit();//用于传递给父组件
            console.log(emit);
        }

    };

    // 技术支持新建联系人点击保存/编辑
    toggleEditSave(e: MouseEvent, index: number): void {
        e.preventDefault();
        const supportGroup = this.support.at(index);
        const isEditing = supportGroup.get('isEditing').value;

        if (isEditing) {
            // 点击“保存”时，禁用输入框
            supportGroup.get('contact').disable();
            supportGroup.get('phone').disable();
            supportGroup.get('time').disable();
        } else {
            // 点击“编辑”时，启用输入框
            supportGroup.get('contact').enable();
            supportGroup.get('phone').enable();
            supportGroup.get('time').enable();
        }

        // 切换编辑状态
        supportGroup.get('isEditing').setValue(!isEditing);
    }

    // 移除联系人信息
    remove(e: MouseEvent, index: number): void {
        e.preventDefault();
        this.support.removeAt(index);
    }

    // 上传图片
    getUpload(files: any, controlName: string) {
        const style = {
            width: undefined,
            height: undefined,
        };
        const imgSize = files[0].size;
        // 限制文件大小和类型
        if (imgSize > 500 * 1024) {
            // 500KB
            this.nzMessage.warning('文件大小不能超过500KB');
            return;
        }
        const type_list = files[0].type.split('/');
        if (type_list.length !== 2 || type_list[1] !== 'png') {
            this.nzMessage.warning('仅支持PNG格式的图片');
            return;
        }
        this.reader.onload = (evt) => {
            if (
                type_list.length === 2 &&
                (type_list[1] === 'jpg' ||
                    type_list[1] === 'png' ||
                    type_list[1] === 'jpeg')
            ) {
                const img: any = new Image();
                img.src = evt.target['result'];
                // 图片加载完成执行下面操作
                img.onload = () => {
                    style.width = img.width;
                    style.height = img.height;
                    controlName === 'onlineServiceImg'
                        ? (this.customerFile = files[0])
                        : (this.userFile = files[0]);
                    controlName === 'onlineServiceImg'
                        ? (this.onlineServiceImg = evt.target['result'])
                        : (this.userDocumentImg = evt.target['result']);
                };
            } else {
                // this.nzMessage.warning('仅支持png格式而且不超过500K的图片');
                return;
            }
        };

        this.reader.readAsDataURL(files[0]);
    }

    // 添加一个联系人信息
    addNewSupport(e: MouseEvent): void {
        e.preventDefault();
        this.support.push(this.createSupportGroup());
    }

    resetForm(): void {
        const params = {
            reset_fields: [
                'technical_support_email',
                'technical_support_phone_show',
                'enterprise_website',
                'enterprise_website_show',
                'copyright_notice',
                'copyright_notice_show',
                'technical_support',
                'technical_support_show',
                'customer_service_qr_code',
                'customer_service_qr_code_show',
                'user_document',
                'user_document_show',
                'user_license',
                'user_license_show',
            ],
        };
    }


}
